// static/js/main.js

// 首页标签切换功能
document.addEventListener('DOMContentLoaded', function() {
    // 标签切换功能
    const tabs = document.querySelectorAll('.tab');
    const storyCards = document.querySelectorAll('.story-card');
    
    if (tabs.length > 0 && storyCards.length > 0) {
        tabs.forEach(tab => {
            tab.addEventListener('click', function() {
                // 移除所有标签的活动状态
                tabs.forEach(t => t.classList.remove('active'));
                
                // 为当前点击的标签添加活动状态
                this.classList.add('active');
                
                // 获取选择的分类
                const category = this.getAttribute('data-category');
                
                // 根据分类显示/隐藏故事卡片
                storyCards.forEach(card => {
                    if (category === 'all' || card.getAttribute('data-category') === category) {
                        card.style.display = 'block';
                    } else {
                        card.style.display = 'none';
                    }
                });
            });
        });
    }
    
    // 登录表单处理
    const loginForm = document.getElementById('loginForm');
    if (loginForm) {
        loginForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const messageEl = document.getElementById('login-message');
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            // 简单的前端验证
            if (!username || !password) {
                showMessage(messageEl, '请填写所有字段', 'error');
                return;
            }
            
            // 显示加载状态
            const submitButton = loginForm.querySelector('button[type="submit"]');
            const originalText = submitButton.textContent;
            submitButton.textContent = '登录中...';
            submitButton.disabled = true;
            
            // 收集表单数据
            const formData = new FormData(loginForm);
            
            // 发送登录请求
            fetch('/user/login/', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': getCookie('csrftoken')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage(messageEl, data.message, 'success');
                    setTimeout(() => {
                        window.location.href = '/';
                    }, 1000);
                } else {
                    showMessage(messageEl, data.message, 'error');
                }
            })
            .catch(error => {
                showMessage(messageEl, '登录过程中发生错误，请稍后重试', 'error');
                console.error('Error:', error);
            })
            .finally(() => {
                // 恢复按钮状态
                submitButton.textContent = originalText;
                submitButton.disabled = false;
            });
        });
    }
    
    // 注册表单处理
    const registerForm = document.getElementById('registerForm');
    if (registerForm) {
        registerForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const messageEl = document.getElementById('register-message');
            const username = document.getElementById('username').value;
            const email = document.getElementById('email').value;
            const password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            
            // 前端验证
            if (!username || !email || !password || !confirmPassword) {
                showMessage(messageEl, '请填写所有字段', 'error');
                return;
            }
            
            if (password !== confirmPassword) {
                showMessage(messageEl, '密码和确认密码不匹配', 'error');
                return;
            }
            
            if (password.length < 6) {
                showMessage(messageEl, '密码长度至少为6位', 'error');
                return;
            }
            
            // 显示加载状态
            const submitButton = registerForm.querySelector('button[type="submit"]');
            const originalText = submitButton.textContent;
            submitButton.textContent = '注册中...';
            submitButton.disabled = true;
            
            // 收集表单数据
            const formData = new FormData(registerForm);
            
            // 发送注册请求
            fetch('/user/register/', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': getCookie('csrftoken')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage(messageEl, data.message, 'success');
                    setTimeout(() => {
                        window.location.href = '/';
                    }, 1000);
                } else {
                    showMessage(messageEl, data.message, 'error');
                }
            })
            .catch(error => {
                showMessage(messageEl, '注册过程中发生错误，请稍后重试', 'error');
                console.error('Error:', error);
            })
            .finally(() => {
                // 恢复按钮状态
                submitButton.textContent = originalText;
                submitButton.disabled = false;
            });
        });
    }
    
    // 故事生成表单处理
    const storyForm = document.getElementById('storyForm');
    if (storyForm) {
        storyForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 显示加载状态
            document.getElementById('loading').style.display = 'block';
            document.getElementById('result').style.display = 'none';
            
            // 收集表单数据
            const formData = new FormData(storyForm);
            
            // 发送生成故事请求
            fetch('/generate/', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': getCookie('csrftoken')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 显示结果
                    document.getElementById('storyTitle').textContent = data.title;
                    document.getElementById('storyContent').textContent = data.content;
                    document.getElementById('result').style.display = 'block';
                } else {
                    alert('生成故事失败: ' + data.message);
                }
            })
            .catch(error => {
                alert('生成故事过程中发生错误，请稍后重试');
                console.error('Error:', error);
            })
            .finally(() => {
                // 隐藏加载状态
                document.getElementById('loading').style.display = 'none';
            });
        });
    }
    
    // 保存故事按钮处理
    const saveBtn = document.getElementById('saveBtn');
    if (saveBtn) {
        saveBtn.addEventListener('click', function(e) {
            e.preventDefault();
            alert('故事已保存（演示）');
        });
    }
});

// 显示消息函数
function showMessage(element, message, type) {
    element.textContent = message;
    element.className = 'message ' + type;
    element.style.display = 'block';
    
    // 3秒后自动隐藏成功消息
    if (type === 'success') {
        setTimeout(() => {
            element.style.display = 'none';
        }, 3000);
    }
}

// 获取CSRF token的函数
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}